package com.csii.activiti.server.core.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.csii.activiti.server.core.constant.CommonConstant;
import com.csii.activiti.server.core.entity.ActManyCondition;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ELUtils {

    private static Pattern regex = Pattern.compile("\\$\\{([^}]*)\\}");

    public static String getSummary(String str,String manyConditionJson,Map<String, Object> data){
        if (StrUtil.isBlank(str)){
            return null;
        }
        Map<String, ActManyCondition> manyConditionMap = null;
        if (null != manyConditionJson){
            manyConditionMap = FormJsonProcessUtils.toManyConditions(manyConditionJson);
        }
        Matcher matcher = regex.matcher(str);
        //使用正则提取参数
        while (matcher.find()) {
            String param = matcher.group(1);
            Object value = data.get(param);
            if (value != null) {
                ActManyCondition actManyCondition;
                if (manyConditionMap != null && ((actManyCondition = manyConditionMap.get(CommonConstant.PREFIX_FORM_DATA + param)) != null || (actManyCondition = manyConditionMap.get(param)) != null)){
                    if (actManyCondition != null && actManyCondition.getValAndLabel() != null){
                        if (actManyCondition.getType().startsWith("radio") || actManyCondition.getType().startsWith("select")){
                            String replaceVal = actManyCondition.getValAndLabel().get(value.toString());
                            if (replaceVal != null){
                                value = replaceVal;
                            }
                        }else if(actManyCondition.getType().startsWith("checkbox")){
                            List<Object> checkboxList = JSONObject.parseArray(value.toString(), Object.class);
                            if (!checkboxList.isEmpty()){
                                ActManyCondition copyManyCondition = actManyCondition;
                                value = checkboxList.stream().map(checkbox-> {
                                    String checkboxKey = checkbox.toString();
                                    String checkboxValue = copyManyCondition.getValAndLabel().get(checkboxKey);
                                    if(checkboxValue == null){
                                        return checkboxKey;
                                    }
                                    return checkboxValue;
                                }).collect(Collectors.joining(","));
                            }
                        }
                    }
                }
                str = str.replace("${" + param + "}", value.toString());
            }
        }
        return str;
    }

}
